<?php
namespace frontend\controllers;

use common\models\User;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\web\Controller;
use yii\web\ServerErrorHttpException;

class HomeController extends Controller
{
    public function actionIndex()
    {
        $model = new User();
        $this->layout = "home";
        return $this->render('index1',['model' => $model]);
    }

    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        if (Yii::$app->request->isPost){
            $model = new \frontend\models\UserLoginForm();
            $data = Yii::$app->request->post();
            $model->password_hash = $data['User']['password_hash'];
            $model->username = $data['User']['username'];
            if ($model->login()){
                return $this->redirect(['video/index']);
            }else{
                return $this->render('index');
            }
        }
//        if ($model->load(Yii::$app->request->post()) && $model->login()) {
//            return $this->goBack();
//        } else {
//            return $this->render('login', [
//                'model' => $model,
//            ]);
//        }
    }

    public function actionSignup()
    {
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if ($data['User']['password_hash'] == $data['User']['repeat_password']){
                $model = new User();
                $model->username = $data['User']['username'];
                $model->password_hash =  Yii::$app->security->generatePasswordHash($data['User']['password_hash']);
                $model->auth_key = Yii::$app->security->generateRandomString();
                if ($model->save(false)){
                    return $this->redirect(['video/index']);
                }
            }else{
                throw new ServerErrorHttpException('密码不一致.');
            }
        }
    }

    //视频模块
    public function actionVideo()
    {
        echo 1;
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->redirect(['home/index']);
    }
}